<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */
namespace app\api\model\dao;

use think\Model;
use think\Db;

class NoteStatistics extends Model
{
    protected $table = 'note_statistics';

    protected $pk = 'id';

    /**
     * 添加统计记录
     *
     */
    public function addNoteStatistics($arrInput)
    {
        $sql = sprintf("insert into %s(cir_id, note_id, userid, pv, create_time) values(%d,%d,%d,%d,%d) on duplicate key update pv=pv+1", $this->table, $arrInput['cir_id'], $arrInput['note_id'], $arrInput['userid'], 1, time());
        return Db::table($this->table)->query($sql);
    }

    /**
     * 根据帖子id和用户id获取统计记录
     *
     */
    public function getNoteStatisticsOne($note_id, $userid)
    {
        $arrCond = [
            'note_id' => ['=', $note_id],
            'userid' => ['=', $userid],
        ];

        return Db::table($this->table)->where($arrCond)->select();
    }

    /**
     * 获取帖子列表
     *
     * @param array $conds
     * @param array $fields
     * @param int $offset
     * @param int $limit
     * @param string $orderby
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getNoteStatistics($conds = [], $fields = [], $offset = 0, $limit = 10000, $orderby = '')
    {
        $this->allowField(true);

        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';

        $arrField = [];
        foreach ($fields as $val) {
            if (in_array($val, $this->field)) {
                $arrField[] = $val;
            }
        }
        empty($arrField) && $arrField = $this->field;

        return Db::table($this->table)->where($arrCond)->limit($offset, $limit)->order($orderby)->field($arrField)->select();
    }

}
